package com.hue.netty.day01.three;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import java.util.Scanner;

/*
    使用netty实现群聊系统的客户端:
        1.发送消息
        2.接收消息
 */
public class Client {
    public EventLoopGroup workerGroup = null;
    public Bootstrap bootstrap = null;

    public Client() {
        try {
            //创建两个工作组
            workerGroup = new NioEventLoopGroup();
            //创建启动器
            bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientChannelInitializer());
            ChannelFuture channelFuture = bootstrap.connect("localhost", Server.PORT).sync();
            Channel channel = channelFuture.channel();
            Scanner sc = new Scanner(System.in);
            while (true){
                String msg = sc.nextLine();
                channel.writeAndFlush(msg);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new Client();
    }
}
